﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace SheepCommon.API.SheepCommands.EChartsCommon
{
    public class SheepReproductiveStateQueryHandler : IRequestHandler<SheepReproductiveStateQueryCommand, Result>
    {
        private readonly IBaseRepository<SheepArchives> _sheepArchivesRepository;

        public SheepReproductiveStateQueryHandler(IBaseRepository<SheepArchives> sheepArchivesRepository)
        {
            _sheepArchivesRepository = sheepArchivesRepository;
        }
        /// <summary>
        /// 种母繁殖状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SheepReproductiveStateQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {

                var sheepReproductiveState = await (from a in await _sheepArchivesRepository.GetAll()
                                                    select new SheepReproductiveStateDto()
                                                    {
                                                        RecordType = a.RecordType,
                                                        name = a.ReproductiveState,
                                                    }).ToListAsync();
                if (request.RecordType != -1)
                {
                    sheepReproductiveState = sheepReproductiveState.Where(c => c.RecordType == request.RecordType).ToList();
                }
                sheepReproductiveState = await (from a in await _sheepArchivesRepository.GetAll()
                                                where a.RecordType == request.RecordType
                                                group a by a.ReproductiveState into a
                                                select new SheepReproductiveStateDto()
                                                {
                                                    name = a.Key,
                                                    value = a.Count()
                                                }).ToListAsync();
                result.Data = sheepReproductiveState;

            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
